<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/14 0014
 * Time: 16:34
 */

namespace app\api\controller;

use app\common\logic\Logic;
use app\common\logic\OpinionBug;
use app\common\logic\Recharge;
use app\common\logic\UserId;
use app\common\model\Emoticon;
use app\common\model\SkillApply;
use app\common\model\Users;
use Carbon\Carbon;
use think\Db;
use think\Request;
use app\common\model\Music;

class Api extends User
{


    /**
     * 获取融云token
     */
    public function token()
    {
        $token = $this->R_token($this->role_id);
        if ($token !== false) api_return(1, '获取成功', $token);
        api_return(0, '服务器繁忙,请稍后重试');
    }


    /**
     * 获取说明文档
     */
    public function explain()
    {
        $id = input('post.id');
        if (!is_numeric($id)) api_return(0, '参数错误');
        $data = Db::name('explain')->where('id', $id)->value('content');
        if (!empty($data)) api_return(1, '获取成功', $data);
        api_return(0, '暂无数据');
    }

    /**
     * Created by xiaosong
     * E-mail:306027376@qq.com
     * 客服列表
     */
    public function service()
    {
        $map['status']     = 1;
        $map['is_service'] = 1;
        $rows = Db::name('admins')->where($map)->field('user_id,nick_name,header_img')->select();

        foreach ($rows as $k => $v){
            $rows[$k]['user_id'] = 'admin'.hashid($v['user_id']);
        }

        api_return(1,'获取成功',$rows);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 筛选分类下用户
     */
    public function screen()
    {

        $data  = input('post.');
        $map   = [];
        $order = '';

        //是否使用距离查询 默认false
        $distance = false;

        $map['a.status']  = 1;
        $map['a.is_use']  = 1;

        if ($data['skill_id']){
            $map['a.skill_id'] = $data['skill_id'];
        }

        if ($data['grade']){
            $map['a.my_grade'] = ['in',$data['grade']];
        }

        if ($data['form_id']){
            $map['a.my_form'] = ['like','%'.$data['form_id'].'%'];
        }

        if ($data['sex']){
            $map['u.sex'] = $data['sex'];
        }

        switch ($data['order']){ //筛选条件

            case 'new': //新人

                $map['a.num'] = ['<=',3];

                break;
            case 'discount': //特惠

                $order = ['a.mini_price'];

                break;
            case 'score': //根据好评排序 评分

                $order = 'a.score desc';

                break;
            case 'online':

                $map['e.online_status'] = 1;

                break;
            case 'city': //同城查询 根据距离查询

                $distance = true;

                break;
            default://热门

                $order = ['a.num'=>'desc','a.score'=>'desc'];

                break;
        }

        $model = new SkillApply();
//        var_dump($map);
//        var_dump($order);exit;
        if ($distance){

            //根据距离查询
            $cache = cache('city_'.$this->user_id);

            //如果当前用户筛选距离有缓存  返回缓存  没有缓存 就查询数据后返回数据并缓存下来  保留30s
            if ($cache){

                $rows = $cache;

            }else{
                $map['a.user_id'] = ['neq',$this->user_id];
                $rows = $model->getCity($map,$this->userExtra('log,lat'),$this->extend('distance'));
                cache('city_'.$this->user_id,$rows,30);
            }

        }else{

            $rows  = $model->getUsers($map,$order);

        }

        api_return(1,'获取成功',$rows);

    }





    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 颜值筛选
     */
    public function vod()
    {

        $map = [];
        $map['a.status'] = 1;

        $model = new \app\common\model\Vod();

        $rows = $model->getRows($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 用户搜索
     */
    public function search()
    {

        $map = [];

        $data = input('post.');

        if ($data['nick_name']){
            if ($data['type'] == 1){
                $map['a.nick_name|a.uuid'] = trim($data['nick_name']);
            }else{
                $map['a.nick_name|a.uuid'] = ['like','%'.trim($data['nick_name']).'%'];
            }
        }


        if ($data['section']){
            $time = ageDate($data['section']);
            $map['a.birthday'] = ['between time',$time];
        }

        if ($data['sex']){
            $map['a.sex'] = $data['sex'];
        }

        if ($data['constellation']){
            $map['a.constellation'] = $data['constellation'];
        }


        $map['a.user_id'] = ['neq',$this->user_id];

        $model = new Users();

        $rows = $model->search($map,$this->user_id);
        api_return(1,'获取成功',$rows);

    }


    /**
     * 坐标用户搜索
     */
    public function latSearch(Request $request)
    {
        $map = [];

        $data = input('post.');

        if ($data['nick_name']){
            $map['a.nick_name|a.uuid'] = ['like','%'.trim($data['nick_name']).'%'];
        }

        if ($data['section']){
            $time = ageDate($data['section']);
            $map['a.birthday'] = ['between time',$time];
        }

        if ($data['sex']){
            $map['a.sex'] = $data['sex'];
        }

        $map['a.user_id'] = ['neq',$this->user_id];
        $userExtra = $request->only(['log','lat']);

        $model = new Users();
        $rows = $model->latSearch($map,$this->user_id,true,$userExtra);

        api_return(1,'获取成功',$rows);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取用户贵族等级
     */
    public function noble()
    {
        $data['noble'] = $this->userExtra('noble_id,noble_time');
        //TODO 判断是否需要使用checkNoble方法更新用户的贵族等级
        $data['rows']  = Db::name('noble')->field('create_time,update_time',true)->order('noble_id')->select();

        if ($data['noble']['noble_time'] > time()){
            $str = '到期';
        }else{
            $str = '已过期';
        }

        Carbon::setLocale('zh');

        $data['noble']['noble_time'] = Carbon::createFromTimestamp($data['noble']['noble_time'])->diffForHumans().$str;
        api_return(1,'获取成功',$data);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 身份认证提交页面
     */
    public function checkView()
    {
        api_return(1,'获取成功',$this->extend('check_explain,face_example,back_example,self_example'));
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 身份认证
     */
    public function check()
    {

        $data = request()->only(['real_name','ID_num','face','back','img'],'post');

        if ($this->userInfo('ID')) api_return(0,'您已实名认证,请勿重复操作');

        if (empty($data['real_name'])){
            api_return(0,'请输入真实姓名');
        }

        if (empty($data['ID_num'])){
            api_return(0,'请输入身份证号码');
        }

        $map['user_id'] = $this->user_id;

        $model = new UserId();

        $item = $model->where($map)->find();
        $data['status'] = 3;

        if ($item){

            if ($item['status'] == 3) api_return(0,'您的身份认证正在审核中,请稍后重试');
            checkId($data['ID_num'],$data['real_name']);
            $result = $item->validate(true)->save($data);
            if (!$result){
                api_return(0,$item->getError());
            }
        }else{
            checkId($data['ID_num'],$data['real_name']);
            $data['user_id'] = $this->user_id;
            $result = $model->saveChange($data);
        }

        if ($result) api_return(1,'提交成功,请耐心等待管理员审核');
        api_return(0,$model->getError());
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 举报用户或房间
     */
    public function report()
    {
        $this->ApiLimit(60,$this->user_id,'每分钟只能举报一次!');

        $data = request()->only(['type','id','reason','imgs','phone','qq'],'post');

        if ($data['type'] == 2) $data['id'] = dehashid($data['id']);

        if (!is_numeric($data['id'])) api_return(0,'参数错误');

        if (empty($data['reason'])) api_return(0,'举报理由不能为空');

        $data['user_id'] = $this->user_id;

        $logic = new Logic();
        $logic->changeTable('reason');
        $result = $logic->save($data);

        if ($result){
            api_return(1,'举报成功');
        }else{
            api_return(0,'系统繁忙,请稍后重试');
        }
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取表情包
     */
    public function getEmoticon()
    {
        $model = new Emoticon();

        $rows  = $model->getEmoticonList();

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据用户id获取头像及昵称
     */
    public function getUserInfo()
    {
        $id = input('post.id');
        if ($id){
            $user_id = dehashid($id);
        }else{
            $user_id = $this->user_id;
        }
        $data = $this->userInfo('nick_name,user_id,header_img',$user_id);

        $data['user_id'] = hashid($data['user_id']);

        api_return(1,'获取成功',$data);

    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 根据群组id获取头像及昵称
     */
    public function getGroupInfo(int $id)
    {
        $data = Db::name('chat_group')->where('group_id',$id)->field('group_id,group_name,img')->find();
        api_return(1,'获取成功',$data);
    }

    public function test()
    {
//        $group_id = cache('userGroup_'.hashid($this->user_id));
//        $data =  Gateway::getUidListByGroup($group_id);

        $data = cache('testGroup_22222');

        //邀约条件
        $orderCondition = cache('fastOrder_'.hashid($this->user_id));

//        dd($orderCondition);

        $model = new SkillApply();
        $map['e.online_status'] = 1;
        $map['a.user_id']       = ['in',$data];
        $map['a.skill_id']      = $orderCondition['skill_id'];
        $map['e.invite']        = 1;

        $field = 'a.user_id,s.skill_name,u.nick_name,u.header_img,a.num,u.sex,u.birthday,a.my_gift_id,a.score';

        $rows = $model->getFastInfo($map);
        api_return($rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 系统管理员头像等信息
     */
    public function sysInfo()
    {
        $id = input('post.id');

        if (strstr($id,"admin")){ //客服信息查询
            $user_id = dehashid(str_replace('admin','',$id));
            if (is_numeric($user_id)){
                $map['user_id'] = $user_id;
                $map['is_service'] = 1;
                $info = Db::name('admins')->where($map)->field('nick_name,header_img')->find();
                if ($info){
                    goto success;
                }
            }
            goto error;
        }

        switch ($id){
            case 'system':
                $info['nick_name']  = '系统管理员';
                $info['header_img'] = $this->extend('sys_header_img');
                break;
            case 'sysOrder':
                $info['nick_name']  = '订单消息';
                $info['header_img'] = $this->extend('sys_header_img');
                break;
            default:
                goto error;
                break;
        }

        success:
        $info['user_id'] = $id;
        api_return(1,'获取成功',$info);

        error:
        api_return(0,'非法参数');
    }

    /**
     * 苹果内购验证
     */
    public function orderCheck($apple_receipt)
    {
        if (empty($apple_receipt)) api_return(0,'参数错误');
        //测试地址
        $url = 'https://sandbox.itunes.apple.com/verifyReceipt';
//        $url = 'https://buy.itunes.apple.com/verifyReceipt';
        cache('data4444',$apple_receipt);

        $check = Db::name('apple_pay')->where('apple_receipt',$apple_receipt)->value('id');

        if ($check){
            api_return(0,'该订单已充值!');
        }

        $json = $this->http_post($url,$apple_receipt);
        $data = json_decode(json_encode($json),true);

        if ($data['status'] === 0 ){
            $row = $data['receipt']['in_app'][0]['product_id'];
            $price = explode('_',$row)[1];

            if (!is_numeric($price)) api_return(0,'非法参数');

            $data = Db::name('users')->where('user_id',$this->user_id)->setInc('money',$price);
            if ($data){
                $map['user_id'] = $this->user_id;
                $map['apple_receipt'] = $apple_receipt;
                Db::name('apple_pay')->insert($map);
                api_return(1,'充值成功');
            }
        }
        api_return(0,'充值失败');
    }

    //curl请求苹果app_store验证地址
    public function http_post($url, $data_string) {
        $curl_handle=curl_init();
        curl_setopt($curl_handle,CURLOPT_URL, $url);
        curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl_handle,CURLOPT_HEADER, 0);
        curl_setopt($curl_handle,CURLOPT_POST, true);
        curl_setopt($curl_handle,CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($curl_handle,CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl_handle,CURLOPT_SSL_VERIFYPEER, 0);
        $response_json = curl_exec($curl_handle);
        $response = json_decode($response_json);
        curl_close($curl_handle);
        return $response;
    }



    public function bug()
    {
        $param = request()->only(['content','on_time','img','phone','qq'],'post');
        $param['user_id'] = $this->user_id;
        $logic = new OpinionBug();
        $res = $logic->saveOpinion($param);
        if($res !== false){
            api_return(1,'反馈成功');
        }
        api_return(0,$logic->getError());
    }


    /**
     * 分享回调页
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function callBack()
    {
        $data = input('post.');
        $coin = self::getExplain($data['type']);

        $str = '分享成功';

        if (isInt($coin)){
            $has = cache($this->user_id.'share_'.$data['type']);
            if (!$has){//今天没有分享过
                Db::name('users')->where('user_id',$this->user_id)->setInc('coin',$coin);
                $str .= ',本次分享获得了'.$coin.'金币';
            }
        }

        api_return(1,$str);

    }
    
    
    /**
     * 获取音乐列表
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function musicList()
    {
        $model = new Music();

        if (!empty(input('keyword'))){
            $map['song_name|singer'] = ['like','%'.trim(input('keyword')).'%'];
        }

        $map['status'] = 1;

        $rows = $model->getList($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * 上传音乐
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function uploadMusic()
    {
        $data = \request()->only(['img','singer','song_name','music_url'],'post');
        $result = Db::name('music')->insert($data);
        if ($result !== false){
            api_return(1,'上传成功');
        }
        api_return(0,'上传失败');

    }


    /**
     * 手动充值
     */
    public function inc()
    {
        $data = \request()->only('r_id,remark,uuid');

        if (is_numeric($data['uuid'])){
            $data['user_id'] = Db::name('users')->where('uuid',$data['uuid'])->value('user_id');
        }else{
            unset($data['uuid']);
            $data['user_id'] = $this->user_id;
        }
        if (!is_int($data['user_id'])){
            api_return(0,'充值账户错误!');
        }

        $model = new Recharge();
        $result = $model->saveChange($data);
        if ($result !== false){
            api_return(1,'申请提交成功,请耐心等待管理员审核!');
        }
        api_return(0,$model->getError());
    }

    /**
     * 获取支付宝充值信息
     */
    public function getRecharge()
    {
        api_return(1,'获取成功',self::getExtend('ali_code,ali_remark,ali_url'));
    }
    
}